package JDBC_Test.park.Dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import JDBC_Test.park.JDBCUtil;
import JDBC_Test.park.Model.ParkingLotModel;
import jdk.nashorn.internal.scripts.JD;

public class ParkingLotDao {

	Connection con = null;
	Statement st = null;
	PreparedStatement ps = null;

	/**
	 * 初始化车位
	 * 
	 * @param num
	 * @throws SQLException
	 */
	public void insert(int num) throws SQLException {
		// TODO Auto-generated method stub
		String sql = "insert into park_lot (park_no,park_state) values(?,?)";

		try {
			con = JDBCUtil.getConnection();
			con.setAutoCommit(false);
			ps = con.prepareStatement(sql);
			for (int i = 1; i <= num; i++) {
				ps.setInt(1, i);
				ps.setString(2, "空闲");
				ps.addBatch();
			}
			ps.executeBatch();
			ps.clearBatch();
			con.commit();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			JDBCUtil.close(con, st, ps);

		}
	}

	/**
	 * 停车修改车位状态
	 * 
	 * @param parkingLotModel
	 * @throws SQLException
	 */
	public void updateState(ParkingLotModel parkingLotModel) throws SQLException {
		// TODO Auto-generated method stub
		String sql = "update park_lot set park_state = ? where park_no = ?";
		try {
			con = JDBCUtil.getConnection();
			ps = con.prepareStatement(sql);
			if (parkingLotModel.getState().equals(1)) {
				ps.setString(1, "已占用");
			} else {
				ps.setString(1, "空闲");
			}
			ps.setInt(2, parkingLotModel.getParkNo());
			ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(con, st, ps);
		}

	}

	/**
	 * 用于停车时车位状态的判断，如果当前车位已被占，则不能正常停车
	 * 
	 * @param parkingLotModel
	 * @return
	 */
	public boolean selectState(ParkingLotModel parkingLotModel) {
		// TODO Auto-generated method stub
		String sql = "select park_state from park_lot where park_no = ?";

		try {
			con = JDBCUtil.getConnection();
			ps = con.prepareStatement(sql);
			ps.setInt(1, parkingLotModel.getParkNo());

			ResultSet rs = ps.executeQuery();
			while (rs.next()) {
				if (rs.getString("park_state").equals("空闲")) {
					return true;
				}
			}

		} catch (Exception e) {
			// TODO: handle exception
		}

		return false;
	}

	/**
	 * 查询所有车位的状态
	 * @throws SQLException 
	 */
	public void selectAll() throws SQLException {
		// TODO Auto-generated method stub
		String sql = "select * from park_lot";
		try {
			con = JDBCUtil.getConnection();
			st = con.createStatement();
			ResultSet rs = st.executeQuery(sql);
			while (rs.next()) {
				ParkingLotModel p = new ParkingLotModel();
				p.setParkNo(rs.getInt("park_no"));
				if (rs.getString("park_state").equals("空闲")) {
					p.setState(0);
				} else {
					p.setState(1);
				}
				System.out.println(p.toString());
			}

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally {
			JDBCUtil.close(con, st, ps);
		}
	}

}
